import { LightningElement, wire } from 'lwc';

import FIRST_NAME_FIELD from '@salesforce/schema/Contact.FirstName';
import LAST_NAME_FIELD from '@salesforce/schema/Contact.LastName';
import ID_FIELD from '@salesforce/schema/Contact.Id';

import { ShowToastEvent } from "lightning/platformShowToastEvent";
import { updateRecord } from "lightning/uiRecordApi";
import { refreshApex } from "@salesforce/apex";
import getSingleContact from '@salesforce/apex/ContactController.getSingleContact';

export default class ContactUpdator extends LightningElement {

    disabled = false;

    @wire(getSingleContact)
    contact;

    get errors() {
        return this.contact.error ? JSON.stringify(this.contact.error) : '';
    }


    handleChange(event) {
        // Display field-level errors and disable button if a name field is empty.
        if (!event.target.value) {
            // 如果值为空，禁用Update按钮，并调用<lightning-input>组件的reportValidity()方法显示字段级校验错误信息
          event.target.reportValidity();
          this.disabled = true;
        } else {
          this.disabled = false;
        }
    }

    updateContact() {
        console.log('updateContact');
        // 通过解构将querySelectorAll的返回结果转成数组类型，然后调用数组的reduce方法对数组中每个元素进行处理
        const allValid = [...this.template.querySelectorAll("lightning-input")].reduce(
            // 循环调用每个<lightning-input>checkValidity()方法校验输入合法性
            (validSoFar, inputFields) => {
                inputFields.reportValidity();
                return validSoFar && inputFields.checkValidity();
            },
            true,
        );
        if (allValid) {
            // Create the recordInput object
            const fields = {};
            fields[ID_FIELD.fieldApiName] = this.contact.data.Id;
            // 在lightning-input上添加的data-开头的属性会在渲染时被保留
            fields[FIRST_NAME_FIELD.fieldApiName] = this.template.querySelector(
              "[data-field='FirstName']",
            ).value;
            fields[LAST_NAME_FIELD.fieldApiName] = this.template.querySelector(
                "[data-field='LastName']"
            ).value;

            // 这里套一层其实是下面一行的简写，因为updateRecord函数要求的参数是record对象（包含fields属性）
            const recordInput = { fields };
            // const recordInput = { 'fields': fields };

            updateRecord(recordInput)
              .then(() => {
                console.log('update success.');
                this.dispatchEvent(
                  new ShowToastEvent({
                    title: "Success",
                    message: "Contact updated",
                    variant: "success",
                  }),
                );
                // Display fresh data in the form
                return refreshApex(this.contact);
              })
              .catch((error) => {
                console.log('update error.');
                this.dispatchEvent(
                  new ShowToastEvent({
                    title: "Error updating record",
                    message: error.body.message,
                    variant: "error",
                  }),
                );
              });
        } else {
            // The form is not valid
            this.dispatchEvent(
                new ShowToastEvent({
                    title: "Something is wrong",
                    message: "Check your input and try again.",
                    variant: "error",
                }),
            );
        }
    }

}